package com.bionet.metaboservice.controller;

import Pathway_enrichment_analysis.EnrichmentByGfj;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.bionet.service_base.utils.Result;
import com.mathworks.toolbox.javabuilder.MWArray;
import com.mathworks.toolbox.javabuilder.MWCellArray;
import com.mathworks.toolbox.javabuilder.MWException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author hzx
 * @create 2021-08-21 23:57
 */
@RestController
@RequestMapping("/metaboservice/enrichbygfj")
public class EnrichByGfjControllor {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");

    public static final String FILE_SEPARATOR = System.getProperty("file.separator");

    public static String getRealFilePath(String path) {
        return path.replace("/", FILE_SEPARATOR).replace("\\", FILE_SEPARATOR);
    }

    @PostMapping("/cuculate")
    public Result cuculateByAlgo(@RequestParam(value = "url", required = true) String url){
        SaSession tokenSession = StpUtil.getTokenSession();
        if (url.equals("example")){
            String path = Thread.currentThread().getContextClassLoader().getResource("static/example.xlsx").getPath();
            if (path.startsWith("/")){
                url = path.substring(1);
            }
        }
        try {
            EnrichmentByGfj enrichByGfj = new EnrichmentByGfj();
            Object[] objects = enrichByGfj.Pathway_enrichment_analysis(1, url);
            MWCellArray s = (MWCellArray) objects[0];
            List<MWArray> mwArrays = s.asList();
            ArrayList<String> strings = new ArrayList<>();
            for (MWArray item : mwArrays) {
                String data = item.toString();
                strings.add(data);
            }
            int length = strings.size() / 3;
            //柱状图1的数据整理
            ArrayList<Object> finalList = new ArrayList<>();
            ArrayList<Object> table = new ArrayList<>();
            table.add("score");
            table.add("amount");
            table.add("product");
            finalList.add(table);
            for (int i = 0;i<length;i++){
                ArrayList<Object> singleItem = new ArrayList<>();
                singleItem.add(Double.parseDouble(strings.get(2*length+i)));
                singleItem.add(Double.parseDouble(strings.get(2*length+i)));
                singleItem.add(strings.get(length+i));
                finalList.add(singleItem);
            }
            //表格整理
            ArrayList<Object> stringTable = new ArrayList<>();
            for (int i = 0; i < length; i++) {
                HashMap<String, String> itemMap = new HashMap<>();
                itemMap.put("Index", strings.get(i));
                itemMap.put("Name", strings.get(length+i));
                itemMap.put("Score", strings.get(2*length+i));
                stringTable.add(itemMap);
            }
//            String realUrl = (String) session.getAttribute("realUrl");
//            String replaceUrl = realUrl.replace(".xlsx", "_AnalysisResult.xlsx");
//            String webUrl = (String) session.getAttribute("url");
//            String replaceWebUrl = webUrl.replace(".xlsx", "_AnalysisResult.xlsx");
//            // 通过工具类创建writer
//            ExcelWriter writer = ExcelUtil.getWriter(replaceUrl);
//            // 一次性写出内容，使用默认样式，强制输出标题
//            writer.write(stringTable, true);
//            // 关闭writer，释放内存
//            writer.close();
//            session.setAttribute("replaceWebUrl", replaceWebUrl);
            tokenSession.set("list", finalList);
            tokenSession.set("stringTable", stringTable);
            return Result.ok().data("list", finalList);
        } catch (MWException e) {
            e.printStackTrace();
            return Result.error().message(e.toString());
        }
    }

    @PostMapping("/upload")
    public Result fileUpload(MultipartFile file, HttpServletRequest req) throws IOException {
        String strUrl = "";
        SaSession tokenSession = StpUtil.getTokenSession();
        // 得到上传时的文件名
        String originName = file.getOriginalFilename();
        if (!originName.endsWith(".xlsx")) {
            return Result.error().message("文件类型不对，必须为xlsx");
        }

        String strFormat = simpleDateFormat.format(new Date());
        String realPath = req.getServletContext().getRealPath("/") + strFormat;
        //String uploadDir = req.getSession().getServletContext().getRealPath("/") + "/upload/" + strFormat;

        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        // 保存文件对象，加上uuid是为了防止文件重名
        String strNewFileName = UUID.randomUUID().toString().replaceAll("-", "") + ".xlsx";
        try {
            file.transferTo(new File(folder, strNewFileName));
            strUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/" + strFormat + strNewFileName;
            HashMap<Object, Object> HashMap = new HashMap<>();
            HashMap.put("fileName", originName);
            HashMap.put("url", strUrl);
            HashMap.put("realUrl", getRealFilePath(realPath) + strNewFileName);
            tokenSession.set("fileName", originName);
            tokenSession.set("url", strUrl);
            tokenSession.set("realUrl", getRealFilePath(realPath) + strNewFileName);
            return Result.ok().data("data", HashMap);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error().message(e.toString());
        }
    }

    @GetMapping("GetSessionData")
    public Result GetSessionData(HttpServletRequest request) {
        SaSession tokenSession = StpUtil.getTokenSession();
        // 获取session中所有的键值
        Set<String> enumeration = tokenSession.keys();
        HashMap<Object, Object> SessionMap = new HashMap<>();
        // 遍历enumeration中的
        for(String item : enumeration) {
            // 根据键值取session中的值
            Object value = tokenSession.get(item);
            // 加入列表
            SessionMap.put(item, value);
        }
        return Result.ok().data("map", SessionMap);
    }
}
